package com.example.casper.jnuexperiment2025;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class BookDetailsActivity extends AppCompatActivity {
    public static final String EXTRA_BOOK_TITLE = "book_title";
    public static final String EXTRA_BOOK_PRICE = "book_price";
    public static final String EXTRA_BOOK_POSITION = "book_position";
    public static final int RESULT_ADD = 1;
    public static final int RESULT_UPDATE = 2;

    private EditText editTextTitle, editTextPrice;
    private int position = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_book);

        editTextTitle = findViewById(R.id.edit_text_book_title);
        editTextPrice = findViewById(R.id.edit_text_book_price);
        Button buttonCancel = findViewById(R.id.button_cancel);
        Button buttonSave = findViewById(R.id.button_save);

        // 检查是否有传递过来的数据，用于更新操作
        Intent intent = getIntent();
        if (intent.hasExtra(EXTRA_BOOK_TITLE)) {
            editTextTitle.setText(intent.getStringExtra(EXTRA_BOOK_TITLE));
        }
        
        if (intent.hasExtra(EXTRA_BOOK_POSITION)) {
            position = intent.getIntExtra(EXTRA_BOOK_POSITION, -1);
        }

        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });

        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = editTextTitle.getText().toString().trim();
                String price = editTextPrice.getText().toString().trim();

                if (!title.isEmpty() && !price.isEmpty()) {
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra(EXTRA_BOOK_TITLE, title);
                    resultIntent.putExtra(EXTRA_BOOK_PRICE, price);
                    
                    if (position >= 0) {
                        resultIntent.putExtra(EXTRA_BOOK_POSITION, position);
                        setResult(RESULT_UPDATE, resultIntent);
                    } else {
                        setResult(RESULT_ADD, resultIntent);
                    }
                    finish();
                }
            }
        });
    }
}